import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @Author YuanYuan
 * @Date 2022/12/2
 * @Time 14:29
 */
@WebServlet("/registered")
public class RegisteredServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String surepassword = req.getParameter("surepassword");
        resp.setContentType("text/html;charset=utf8");
        try {

            //判断数据库中是否有同名用户
            if(null != UserDAO.selectByName(username)) {
                resp.getWriter().write("该用户已存在,请重新输入用户名");
                return;
            }
            //判断两次密码输入是否一致
            if (null!=password && null!= surepassword && !password.equals(surepassword)) {
                resp.getWriter().write("两次密码输入不一致");
                return;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //创建用户
        User user = new User();
        user.setUserName(username);
        user.setUserPassword(password);
        try {
            UserDAO.insert(user);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        resp.setStatus(302);
        resp.sendRedirect("login.html");

    }
}
